package protocols;

import exceptions.ExAddressInput;


public class IPv4 implements EthernetIIPayload {
	
	static final int version = 4;
	private int header_length;
	private int TOS;
	private int tot_length;
	private int id;
	private int flags;
	private int frag_offset;
	private int TTL;
	private int protocol;
	private int CRC;
	private IPv4.IPv4address sourceIP;
	private IPv4.IPv4address destIP;
	private IPv4payload packetdata;
	private int padding;
	
	
	public static class IPv4address{		
		int byte1, byte2, byte3, byte4;
		public IPv4address(String s) throws ExAddressInput {//za dohvatanje IP adrese iz stringa tipa 127.0.0.1
			try {String[] a=s.split("[.]");
			byte1 = Integer.parseInt(a[0].trim());
			byte2 = Integer.parseInt(a[1].trim());
			byte3 = Integer.parseInt(a[2].trim());
			byte4 = Integer.parseInt(a[3].trim());
			} catch (Exception e){
				throw new ExAddressInput("Greska u nosu IP adrese");
			}
			if ( (byte1>255) || (byte2>255) || (byte3>255) || (byte4>255))
				throw new ExAddressInput("Greska u nosu IP adrese");
		}
		@Override
		public String toString(){
			return new String(byte1+"[.]"+byte2+"[.]"+byte3+"[.]"+byte4);
		}
		public String toString1(){ // za formiranje stringa hexa adrese 45fe3ba9
			String s = new String();
			s = String.format("%02x%02x%02x%02x",byte1,byte2,byte3,byte4);
			return s;
		}
	}
	public int length(EthernetIIPayload payload) {
		// TODO Auto-generated method stub
		return 0;
	}

	public IPv4(int header_length, int TOS, int id, int flags, int frag_offset, int TTL, int protocol, int CRC, IPv4.IPv4address sourceIP, IPv4.IPv4address destIP, IPv4payload packetdata, int padding){
		
		this.CRC = CRC;
		this.destIP = destIP;
		this.flags = flags;
		this.frag_offset = frag_offset;
		this.header_length = header_length;
		this.id = id;
		this.padding = padding;
		this.protocol = protocol;
		this.sourceIP = sourceIP;
		this.TOS = TOS;
		this.TTL = TTL;
		this.sourceIP=sourceIP;
		this.destIP=destIP;
		this.packetdata=packetdata;
	}
	public IPv4(int TTL, int protocol, IPv4.IPv4address sourceIP, IPv4.IPv4address destIP, IPv4payload packetdata){
		this(5,0,0,0,0,TTL,protocol,0,sourceIP,destIP,packetdata,0);
	}
	public IPv4(int protocol, IPv4.IPv4address sourceIP, IPv4.IPv4address destIP, IPv4payload packetdata){
		this(5,0,0,0,0,64,protocol,0,sourceIP,destIP,packetdata,0);
		this.tot_length=20+packetdata.length();
	}

	public int length() {
		return tot_length;
	}
}
